apiready = function() {
seajs.use(['../../V', "../../api", "../../jquery", "../../app", "../../service"], function(V, $api, $, $app, service) {
  $app.ready();
    var vm = {
        el: '.container',
        data: {
            list: '',
            address_id: '',
            cart_ids: '',
            options: '',
            pay_key: '',
            money: '',
            couponList: '',
            activeCoupon: '',
            text_p: '',
            selectTxt: '不使用优惠券',
            selectCoupon: '',
            is_group: false,
            goodsMoney: 0,
            couponIndex: 0,
            shopIndex: -1,
            shopBol: false, //--是否使用店铺优惠
            payCloseWin: '', //--上个窗口名字
            buy_now: false //--是否拼团
        },
        methods: {
            init: function() {
                this.getList();

            },
            getList: function(et) {
                var unionid = $api.getStorage("shop_unionid"),
                    self = this;
                var values = {
                    unionid: unionid
                };
                if (this.cart_ids != '') {
                    values.cart_ids = this.cart_ids;
                } else {
                    values.options = this.options;
                }
                $app.ajax(service.buyConfirmOrder, {
                    data: {
                        values: values
                    }
                }, function(res) {
                    console.log("order: " + JSON.stringify(res));
                    if (res.code == 0 && res.data != '' && res.data != null) {
                        self.list = res.data;
                        self.sumTotalMoney();
                    } else {
                        $api.setTimeout(function() {
                            api.closeWin();
                        }, 2000);
                    }
                });
            },
            //--提交订单，去支付
            goCreateOrderSubmit: function() {
                var self = this;
								if (!$api.getStorage('Vstatus')) {
									$app.toast("体验更多功能，请前往登录")
								}else{
									var shop_com = this.$refs.orderGoodsFather.querySelectorAll(".shop-msg-txt")
	                var shop_cou = this.$refs.orderGoodsFather.querySelectorAll(".order-goods-coupon")
	                var values = {},
	                    _comments = [],
	                    coupons = [],
	                    is_group = false;
	                values.unionid = $api.getStorage("shop_unionid");
	                values.address_id = this.list.address.address_id;
	                for (var i = 0; i < shop_com.length; i++) {
	                    if (shop_com[i].value != '') {
	                        if (shop_com[i].value > 300) {
	                            $app.toast(shop_com[i].dataset.name + "，留言字数过多，店铺留言最大为300字！");
	                            return;
	                        }
	                        _comments.push(shop_com[i].dataset.shopcode + ',' + (shop_com[i].value || ''));
	                    }
	                }
	                for (var i = 0; i < shop_cou.length; i++) {
	                    if (shop_cou[i].dataset.couponid != 'null') {
	                        coupons.push(shop_cou[i].dataset.shopcode + ',' + (shop_cou[i].dataset.couponid));
	                    }
	                }
	                values.coupons = coupons.length <= 0 ? '' : coupons.join("|");
	                values.comments = _comments.length <= 0 ? '' : _comments.join("|");
	                if (values.address_id == "" || values.address_id == undefined) {
	                    $app.toast("请添加地址信息！");
	                    return;
	                }
	                if (this.options != "") {
	                    values.options = this.options;
	                    is_group = this.options.split(",")[2] == "1" ? true : false;
	                } else {
	                    values.cart_ids = this.cart_ids;
	                }
	                $app.ajax(service.cartGenerateOrder, {
	                    data: {
	                        values: values
	                    }
	                }, function(res) {
	                    console.log("order_zf：" + JSON.stringify(res));
	                    //{"code":0,"message":"成功","data":{"total_amount":0.01,"pay_key":"2018080317001097549757"}}
	                    if (res.code == 0) {
	                        self.pay_key = res.data.pay_key;
	                        self.money = res.data.total_amount;
	                        if (self.money == 0) {
	                            $app.openWin("buyOrderPayResult", {
	                                money: '0.00',
	                                name: self.payCloseWin,
	                                is_group: is_group
	                            });
	                        } else {
                              self.wxPay(self.pay_key,self.money)
                              return
	                            // $app.openWin("buyOrderPayWay", {
	                            //     pay_key: self.pay_key,
	                            //     money: self.money,
	                            //     is_group: is_group,
	                            //     name: self.payCloseWin
	                            // });
	                        }
	                        api.sendEvent({
	                            name: 'lisentCart'
	                        });
	                    } else {
	                        alert("订单提交失败！");
	                    }
	                });
								}
            },
            wxPay:function(pay_key,money){
              var wxPay = api.require('wxPay'),that=this;
              $app.ajax(service.buyOrderPayment, {
                  data: {
                      values: {
                          unionid: $api.getStorage("shop_unionid"),
                          pay_key: pay_key,
                          pay_id: 3,
                          from: 'shop_app'
                      }
                  }
              }, function(res) {
                if (res.code == 0) {
                  wxPay.payOrder({
                      orderId: res.data.prepayid,
                      mchId: res.data.partnerid,
                      nonceStr: res.data.noncestr,
                      timeStamp: res.data.timestamp,
                      package: res.data.package,
                      sign: res.data.sign,
                      apiKey: res.data.appid
                  }, function(ret, err) {
                      //console.log(self.money);
                      if (ret.status) {
                          //支付成功
                          $app.openWin("buyOrderPayResult", {
                              money: money
                          });
                          api.sendEvent({
                              name: 'payBackGoods_'
                          });
                      } else {
                          api.toast({
                              msg: '支付失败！',
                              duration: 2000,
                              location: 'middle'
                          });
                      }
                  });
                }
              })

            },
            //--去添加地址
            goOrderAddressAdd: function(et) {
                $app.openWin('buyAddressAdd');
            },
            //--地址选择
            orderAddressSelect: function(et) {
                $app.openWin("buyAddressSelect", {
                    address_id: this.list.address.address_id
                });
            },
            //--使用优惠券
            orderUseCoupon: function(et) {
                var index = +et.currentTarget.dataset.index;
                var data = et.currentTarget.dataset.data;
                if (data == "null") {
                    this.$refs.shopCouponList.style.display = 'none';
                    return;
                } else {
                    this.couponList = JSON.parse(data);
                    this.$refs.shopCouponList.style.display = 'block';
                }
                this.selectCoupon = et.currentTarget;
                this.activeCoupon = et.currentTarget.parentNode.querySelectorAll(".shopTotalMoney")[0];
                this.text_p = et.currentTarget.querySelectorAll("p")[0];
                if (index == this.shopIndex) {
                    this.shopBol = true;
                } else {
                    this.shopBol = false;
                    this.couponIndex = 0;
                }
                this.shopIndex = index;
            },
            //--选择优惠券
            orderSelectCoupon: function(et) {
                this.couponIndex = +et.currentTarget.dataset.index;
                var total = document.querySelector("#orderTotalMoney");
                var total_money = +total.dataset.money;
                var money = +et.currentTarget.dataset.money;
                var b_money = +this.activeCoupon.dataset.money;
                var a_money = b_money - money;
                var t_money = total_money - money;
                this.activeCoupon.innerHTML = "¥" + (a_money > 0 ? a_money : 0).toFixed(2);
                total.innerHTML = '¥' + (t_money > 0 ? t_money : 0).toFixed(2);
                if (money == 0) {
                    this.text_p.innerHTML = '不使用优惠券';
                } else {
                    this.text_p.innerHTML = '省' + money.toFixed(2) + "，店铺活动";
                }
                this.selectCoupon.dataset.couponid = et.currentTarget.dataset.couponid;
                this.closeSelectCoupon();
            },
            //--关闭优惠券选择框
            closeSelectCoupon: function() {
                this.$refs.shopCouponList.style.display = 'none';
            },
            sumTotalMoney: function() {
                var coupon = this.list.shop_list || '';
                var total = this.list.goods_amount;
                var sum = 0;
                if (coupon != '') {
                    for (var i = 0; i < coupon.length; i++) {
                        if (coupon[i].coupon_list.length > 0) {
                            var temp = +coupon[i].coupon_list[0].amount;
                            sum += temp;
                        }
                    }
                }
                this.goodsMoney = sum.toFixed(2);
            },
            //--去商品详情
            goGoodsDetail: function(et) {
                var is_group = et.currentTarget.dataset.group == '1' ? true : false;
                var goods_id = et.currentTarget.dataset.goodsid;
                $app.goGoodsDetail(goods_id, is_group);
            }
        },
        mounted: function() {
            var self = this;
            api.setStatusBarStyle({
                style: 'dark',
                color: ''
            });
            api.sendEvent({
                name: 'payBackGoods_'
            });
            api.sendEvent({
                name: 'payBackCart_'
            });
            //--支付页面回来更新地址
            api.addEventListener({
                name: 'payBackCart_'
            }, function(ret, err) {
                api.closeWin();
            });

            //--选择地址回来更新地址
            api.addEventListener({
                name: 'addressSelect_'
            }, function(ret, err) {
                self.list.address = ret.value.address;
            });
            //--没有地址时，添加地址直接返回
            api.addEventListener({
                name: 'addressAdd_',
            }, function(ret, err) {
                if (ret.value.address != undefined && ret.value.address != null && ret.value.address != '') {
                    self.list.address = ret.value.address;
                }
            });
        },
        created: function() {
            this.cart_ids = api.pageParam.cart_ids || ''; //--购物车过来
            this.options = api.pageParam.options || ''; //--商品详情过来
            this.payCloseWin = api.pageParam.prve; //--上个窗口的名字
            if (this.options != '') {
                this.buy_now = this.options.split(",")[2] == '1' ? true : false;
            }
            this.init();
        }
    };
    var newVue = new Vue(vm);
    var even = function() {

    }
    even();
})
}
